<template>
	<div class="scrapeCard">
    <div class="scrape-card-main">
      <div class="ggl_tit"></div>
      <div class="ggl" id="top">
        <div class="info" id="info" :style="{display: displayAttr}">
          <span class="prompt">{{ promptMsg }}</span>
        </div>
        <div class="canvas-wrap">
          <canvas v-show="!showGGbtn" id="mycanvas" class="canvas" type="2d" @touchstart="onTouchStart" @touchend="onTouchEnd" @touchmove="onTouchMove"></canvas>
        </div>
        <div v-if="showGGbtn" class="ggl-btn-bg">
          <div class="ggl-btn" @click="handleShowGGbtn">点我刮奖</div>
        </div>
      </div>
      <div class="x-same ggl_top_dzp" style="margin-top:0;">
        <div class="x-img">
          <img src="https://img.wifenxiao.com/h5-wfx/images/marketGame/scrapeCard/ggl-dot.png">
          <strong>活动奖品</strong>
        </div>
        <div class="x-cont-box">
          <ul class="prize-list" v-if="gameprizeinfo && gameprizeinfo.length > 0">
            <li>一等奖：{{ gameprizeinfo[0].msg }} </li>
            <li>二等奖：{{ gameprizeinfo[1].msg }} </li>
            <li>三等奖：{{ gameprizeinfo[2].msg }} </li>
            <li>普通奖：{{ gameprizeinfo[3].msg }}</li>
          </ul>
        </div>

      </div>
      <div class="x-same ggl_int_dzp">
        <div class="x-img">
          <img src="https://img.wifenxiao.com/h5-wfx/images/marketGame/scrapeCard/ggl-dot.png">
          <strong>活动时间</strong>
        </div>
        <div class="x-cont-box">
          <p>{{ gameinfo.start_time }} 至 {{ gameinfo.end_time }}</p>
        </div>
      </div>
      <div class="x-same ggl_int_dzp">
        <div class="x-img">
          <img src="https://img.wifenxiao.com/h5-wfx/images/marketGame/scrapeCard/ggl-dot.png">
          <strong>活动规则</strong>
        </div>
        <div class="x-cont-box">
          <p style="white-space: pre-wrap;word-wrap: break-word;">{{ gameinfo.description }}</p>
          <p v-if="gameinfo.cost_point > 0">游戏消耗{{ point_name }} {{ gameinfo.cost_point }}</p>
          <p v-if="gameinfo.give_point > 0">参与游戏即送{{ gameinfo.give_point }}{{ point_name }},
            <span v-if="gameinfo.give_point_to_no_prize_only == 1">仅送给未中奖的用户.</span>
          </p>
        </div>
      </div>
      <div class="win-record x-same">
        <div class="x-img">
          <img src="https://img.wifenxiao.com/h5-wfx/images/marketGame/scrapeCard/ggl-dot.png">
          <strong>中奖排名</strong>
        </div>
        <div class="x-cont-box">

          <div class="win-nav">
            <span>昵称</span>
            <span>奖品</span>
            <span>等级</span>
            <span>中奖时间</span>
          </div>
          <div class="win_list_con">
            <ul>
              <wx-scroll-view :scroll-y="true" style="height:250px" @scrolltolower="onLoad">
               <li v-for="(item,index) in winerLists" :key="index">
                  <span class="win-name">{{ item.nickname }}</span>
                  <span class="win-award win-award-span">{{ item.winer }}</span>
                  <span class="win-award">{{ item.level }}</span>
                  <span class="win-time">{{ item.create_time }}</span>
                </li>
              </wx-scroll-view>
            </ul>
          </div>
        </div>
        <div class="my-prize"><a @click="JumpTo">查看我的奖品&gt;</a></div>
      </div>
    </div>

    <game-result-dialog
      :visible.sync="gameResultVisible"
      :game_prize_id="game_prize_id"
      :getGamePrize="getGamePrize"
      @gameReload="gameReload"></game-result-dialog>
    <shop-code ref="shopCode" :fromType="1"></shop-code>

  </div>
</template>

<script>
  var c1 // 画布
  var ctx	// 画笔
  var ismousedown	// 标志用户是否按下鼠标或开始触摸
  var fontem = parseInt(window.getComputedStyle(document.documentElement, null)['font-size'])
  var bstop = 1

  import Vue from 'vue'
  import { List } from 'vant'
  Vue.use(List)
  import gameResultDialog from '../components/gameResultDialog'
  import { activityGame, playGames } from '@/api/marketGame/gameList'
  import { refreshPage, mpShare } from '@/utils/utils'
  import small from '@/smallapp/small'
  import ShopCode from '@/components/ShopCode'
  import SmallLogin from '@/components/SmallLogin/smallLogin.vue'
  export default Vue.extend({
    name: 'index',
    data() {
      return {
        promptMsg: '还需要接着刮哦...',
        showGGbtn: true,
        loading: false,
        finished: false,
        gameResultVisible: false, // 游戏结果弹窗
        rotateWheel: 0,

        displayAttr:"none",
        show:false, // 是否刮卡完成
        clearPoints:[],
        canvasWidth:0,
        canvasHeight:0,
        // size:16,
        r:30,
        scale:0.5, // 刮出了总区域50%即发起抽奖
        totalArea:0, //刮卡总区域
        stepClear:1,
        need_subscribe: 0,
        gameinfo: {},
        gameprizeinfo: [],
        point_name: '',
        cost_point: '',
        give_point: '',
        winerLists: [],
        shareInfo:{},
        postData: {
          type: 7,
          id: '',
          order_id: '',
          p: 1
        },
        game_prize_id: '', // 获奖数据
        getGamePrize: false, // 中奖或是未中奖
        smallQuery: {}
      }
    },
    components: {
      gameResultDialog,
      // shareShade
      ShopCode
    },
    methods: {
      onLoad() {
        this.activityGameFn()
      },
      JumpTo() {
        this.$JumpName(this, 'prize-list')
      },
      /**
       * 获取中奖信息
       */
      handleClickRotate() {
        const param = Object.assign({}, this.postData)
        param.id = this.$route.query.id
        playGames(param).then(res => {
          this.gameResultVisible = true
          // 清楚canvas
          ctx && ctx.clearRect(0, 0, c1.width, c1.height);
          const resData = res.data
          if (res.status == 1) {
            if (resData.game_parameter) {
              this.game_prize_id = res.data.game_parameter.game_prize_id
              if (resData.game_parameter.ds && resData.game_parameter.ds.winning_value == 1) {
                this.getGamePrize = true
                this.promptMsg = resData.game_parameter.ds.prize
              } else {
                this.getGamePrize = false
                this.promptMsg = '谢谢惠顾！'
                if (resData.game_parameter.notwinning) {
                  const baseMsg = this.gameinfo.give_point > 0 ? `,别灰心参与也有${this.gameinfo.give_point}${this.point_name}` : ''
                  const noPrizeMsg = resData.game_parameter.notwinning + baseMsg
                  this.game_prize_id.noPrizeMsg = noPrizeMsg
                }
              }
            }
          } else {
            this.getGamePrize = false
            this.$Error(res.msg)
          }
        })
      },
      /**
       * 游戏的默认请求
       */
      activityGameFn() {
        const param = Object.assign({}, this.postData)
        param.id = this.$route.query.id
        activityGame(param).then(res => {
          if (res.status == 1) {
            const resData = res.data
            this.need_subscribe = resData.need_subscribe
            if (resData.need_subscribe == 1) {
              this.$refs.shopCode.dialogVisible = true
              return false
            }
            this.gameprizeinfo = resData.gameprizeinfo
            this.winerLists = this.winerLists.concat(resData.winer_lists)
            this.gameinfo = resData.gameinfo
            this.point_name = resData.point_name
            this.cost_point = resData.cost_point
            this.give_point = resData.give_point
            // 加载状态结束
            this.loading = false
            if (resData.winer_lists.length < 10) {
              this.finished = true
            }
            this.shareInfo = {
              title: resData.jsapi_title,
              imgUrl: resData.jsapi_img,
              shareParam: resData.jsapi_url.split('?')[1]
            }

            this.postData.p++
            mpShare(true, false, '/activity/pages/scrapeCard/index', this.shareInfo)
          } else {
            // this.$Error(res.msg)
          }
        })
      },
      init() {
        const param = Object.assign({}, this.postData)
        param.id = this.smallQuery.id
        // console.log('init..***', this.$route)
        if (this.smallQuery.order_id) {
          param.order_id = this.smallQuery.order_id
        }
        this.postData = param
        // 恢复初始值
        this.showGGbtn=true;
        bstop=1;
        this.activityGameFn();
      },
      // 关闭抽奖弹窗重新渲染
      gameReload(){
        refreshPage(this)
        this.init()
      },

      // 点击刮奖按钮
      handleShowGGbtn(){
        this.showGGbtn = false;
        /* 开始初始化画布 */
        c1 = document.querySelector('#mycanvas');
        const canvasWrap = document.querySelector('.canvas-wrap');
        canvasWrap.$$getBoundingClientRect().then(res => {
          // // console.log(res)
          c1.width = this.canvasWidth=res.width;
          c1.height =this.canvasHeight= res.height;
          this.totalArea= res.width*res.height;

          c1.$$prepare().then(domNode => {
            ctx = domNode.getContext('2d');
            // // console.log(ctx)
            // 初始化
            this.initCanvas()
          })
        })
      },

      drawBeauty(beauty){
        ctx.drawImage(beauty, 0, 0 ,this.canvasWidth, this.canvasHeight);
        ctx.globalCompositeOperation = "source-over";
        //把这个属性设为这个就可以做出圆形橡皮擦的效果
        //有些老的手机自带浏览器不支持destination-out,下面的代码中有修复的方法
        ctx.globalCompositeOperation = 'destination-out';
        this.displayAttr="block";
      },

      initCanvas() {
        const that=this;
        document.querySelector('#mycanvas').$$getNodesRef().then(nodesRef => {
          nodesRef.node(res => {
            //绘制  头像
            const beauty = res.node.createImage();
            beauty.src = 'https://img.wifenxiao.com/h5-wfx/images/marketGame/scrapeCard/gglbg2-1.png';
            beauty.onload = function () {
              that.drawBeauty(beauty);
            }
          }).exec()
        })

        // var beauty = new Image();
        // beauty.src = 'https://img.wifenxiao.com/h5-wfx/images/marketGame/scrapeCard/gglbg2-1.png';
        // if(beauty.complete){
        //   this.drawBeauty(beauty);
        // }else{
        //   beauty.onload = () => {
        //     this.drawBeauty(beauty);
        //   };
        //   beauty.onerror = function(){
        //     window.alert('请重试');
        //   };
        // }
      },

      // ctx.clearRect模拟圆形擦除 //圆心(x,y)，半径radius
      clearArc(x,y,radius){
        var calcWidth=radius-this.stepClear;
				var calcHeight=Math.sqrt(radius*radius-calcWidth*calcWidth);
				
				var posX=x-calcWidth;
				var posY=y-calcHeight;
				
				var widthX=2*calcWidth;
				var heightY=2*calcHeight;
				
				if(this.stepClear<=radius){
					ctx.clearRect(posX,posY,widthX,heightY);
					this.stepClear+=1;
					this.clearArc(x,y,radius);
				}
      },

      // 刮卡效果
      eraser(e,bool){
        let len = this.clearPoints.length;
        let count = 0
        let x = e.touches[0].x, y = e.touches[0].y;
        let x1 = x - this.r/2;
        let y1 = y - this.r/2;
        if(bool){
          this.clearPoints.push({
            x1: x1,
            y1: y1,
            x2: x1 + this.r,
            y2: y1 + this.r
          })
        }
        for (let val of this.clearPoints){
          if(val.x1 > x || val.y1 > y || val.x2 < x || val.y2 < y){
            count++;
          }else{
            break;
          }
        }
        if(len === count){
          this.clearPoints.push({
            x1: x1,
            y1: y1,
            x2: x1 + this.r,
            y2: y1 + this.r
          })
        }

        if (this.clearPoints.length && this.r * this.r * this.clearPoints.length > this.scale * this.totalArea){
          this.show = true;
        }
        this.stepClear=1
        this.clearArc(x1, y1, this.r);
      },

      onTouchStart(e){
        this.eraser(e,true);
      },
      onTouchMove(e){
        this.eraser(e,);
      },
      onTouchEnd(e){
        if(this.show){
          this.getGift();
        }
      },

      //判断是否达到条件
      // isReach() {
      //   //得到canvas的全部数据
      //   var a = ctx.getImageData(0,0,this.canvasWidth,this.canvasHeight);
      //   var result = this.canvasWidth * this.canvasHeight
      //   var j=0;
      //   for(var i=3;i<a.data.length;i+=4){
      //     if(a.data[i]==0)j++;
      //   }
      //   //当被刮开的区域等于一半时，则可以开始处理结果
      //   if(j >= result / 2){
      //     return true;
      //   }
      //   return false;
      // },

      getGift() {
        if(bstop){
          bstop=0
          this.handleClickRotate()
        }
      }

    },
    mounted() {
      window.addEventListener('wxload', (query) => {
        // scene=3015nqnq0b2f39e0d
        this.smallQuery = Object.assign(this.$route.query, query)
        // console.log('this.smallQuery11', this.smallQuery)
        // this.init(this.smallQuery)
        this.init()
      })
      
      window.addEventListener('wxshow', () => {
        small.HandleShareParams()
        if(!small.checkLogin()) {
          this.$refs.smalllogin.openSmallLoginPop()
        }
      })
      window.$$subscribe('loginReload', reload => {
        if (reload) {
          this.init()
        }
      })
    }
  })
</script>

<style lang="scss">
  .scrapeCard{
    padding: 1px 0;
    background: url(https://img.wifenxiao.com/h5-wfx/images/marketGame/scrapeCard/gglbg-1.png) no-repeat #ff2439;
    background-size:100% auto;
    .ggl_tit {
      margin: 68px auto 0;
      width: 70%;
      height: 140px;
      background: url(https://img.wifenxiao.com/h5-wfx/images/marketGame/scrapeCard/ggl_tit-1.png) no-repeat;
      background-size: contain;
      background-size: 100% 100%;
    }

    .ggl {
      position: relative;
      width: 100%;
      height: 646px;
      background: url(https://img.wifenxiao.com/h5-wfx/images/marketGame/scrapeCard/ggl_content-1.png) no-repeat center center;
      background-size: 100% 100%;

      .info {
        position: absolute;
        top: 170px;
        left: 2.5%;
        width: 95%;
        height: 100%;
        text-align: center;

        span {
          display: block;
          font-size: 36px;
        }

        .prompt {
          line-height: 280px;
        }
      }

      .canvas-wrap {
        position: absolute;
        top: 174px;
        left: 82px;
        width: 78%;
        height: 310px;
        line-height: 310px;
        text-align: center;
        z-index: 2;
        border-radius: 30px;
        .canvas{
          width:100%;
          height:100%;
        }
      }

      .ggl-btn-bg{
        position: absolute;
        top: 174px;
        left: 82px;
        width: 78%;
        height: 310px;
        z-index:3;
        border-radius: 30px;
        background:url(https://img.wifenxiao.com/h5-wfx/images/marketGame/scrapeCard/gglbg2-1.png) no-repeat;
        background-size:100% 100%;
      }

      .ggl-btn {
        position: absolute;
        top: 50%;
        left: 0;
        right:0;
        margin:0 auto;
        transform: translateY(-50%);
        z-index: 3;
        text-align: center;
        width: 284px;
        height: 63px;
        background: linear-gradient(left, #ff4200, #ff6200);
        background: -ms-linear-gradient(left, #ff4200, #ff6200);
        background: -webkit-linear-gradient(left, #ff4200, #ff6200);
        background: -moz-linear-gradient(left, #ff4200, #ff6200);
        background: -o-linear-gradient(left, #ff4200, #ff6200);
        box-shadow: 0px 4px 10px 1px rgba(255, 162, 120, 0.55);
        border-radius: 32px;
        line-height: 63px;
        font-size: 26px;
        color: #fff;
      }
    }

    .x-same {
      margin: 0 20px;
      color: #fff;
      .x-img {
        margin: 40px 0 30px;
        position: relative;

        img {
          display: block;
          width: 184px;
          margin: 0 auto;
        }

        strong {
          position: absolute;
          top: -10px;
          left: 50%;
          transform: translateX(-53%);
          font-size: 30px;
          font-family: SimHei;
          font-weight: bold;
          font-style: italic;
          letter-spacing: 2px;
          color: #fff;
          line-height: 48px;
          text-shadow: 0px 8px 4px rgba(81, 81, 81, 0.19);
        }
      }

      &.ggl_top_dzp ul li {
        line-height: 60px;
        margin-left: 70px;
        font-size: 28px;
        display: block;
        color: #333;
        font-weight: bold;
        // font-family: 'PingFang SC Medium',SimHei;
      }

      &.ggl_int_dzp p {
        line-height: 50px;
        // margin-left:5%;
        font-size: 24px;
        color: #333;
        text-align: left;
      }

      &.win-record li span {
        float: left;
        width: 25%;
        border-bottom: dashed 2px #ffcfca;
        height: 100px;
        line-height: 100px;
        font-size: 24px;
        color: #333;
        font-weight: 400;
        white-space: nowrap;
        text-align: center;
        &:nth-child(3){
          width: 22%;
        }
        &:nth-child(4){
          width: 28%;
        }
      }

      &.win-record {
        .x-cont-box {
          padding-top: 15px;
          .win-nav {
            border-bottom: 2px solid #ffcfca;
            font-size: 0;
            span {
              width: 25%;
              text-align: center;
              font-size: 24px;
              color: #ff3d3a;
              font-weight: bold;
              height: 75px;
              line-height: 75px;
              display: inline-block;
            }

          }
          .win_list_con{
            height: 510px;
            overflow: auto;
            ul{
              span.win-level{
                text-align: left
              }
              span.win-name{
                text-align: center
              }
              li{
                overflow:hidden;
              }
            }
          }
        }
        .my-prize{
          width:223px;
          height:57px;
          border:2px solid #ffb44a;
          border-radius:30px;
          text-align: center;
          line-height: 57px;
          margin: 20px auto;
          a {
            color: #ffb44a;
          }
        }
      }
    }
    .x-cont-box {
      width: 88.5%;
      margin: 0 auto;
      padding: 7% 4.2%;
      background: #fff7ef;
      border: 6px solid #eb2934;
      box-shadow: 0px 8px 0px 0px rgba(81, 81, 81, 0.11);
      border-radius: 20px;
    }
  }
  .win-award-span{
    text-overflow: ellipsis;
    overflow: hidden;
  }
</style>
